package com.vpen.websocket.demo.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.vpen.websocket.demo.ReqMessage;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/9/1 14:30
 */
@Slf4j
@Component
@ServerEndpoint("/websocket/{user}")
@EqualsAndHashCode
public class ChatHelloSocket {


    private static final Map<String, Session> POOL = new ConcurrentHashMap<>();


    @OnOpen
    public void onOpen(Session session, @PathParam("user") String user) throws IOException {
        log.debug("与{},建立连接", user);
        POOL.put(user, session);
    }


    @OnClose
    public void onClose(@PathParam("user") String user) throws IOException {
        log.debug("与{},断开连接", user);
        POOL.remove(user);
    }

    /**
     * @param session -
     * @param message -
     * @author 韦鹏
     * @date 2022/9/1 16:54
     **/
    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        ReqMessage msg = JSONUtil.toBean(message, ReqMessage.class);
        sendToUser(msg, session);
        log.debug("收到消息：{}", message);
    }


    public void sendToUser(String appId, String message) throws IOException {
        Session session = POOL.get(appId);
        session.getAsyncRemote().sendText(message);
    }

    public void sendToUser(ReqMessage msg, Session fromSession) throws IOException {
        Session session = POOL.get(msg.getToUser());
        if (ObjectUtil.isNull(session)) {
            log.debug("用户不在线");
            fromSession.getAsyncRemote().sendText("用户不在线");
            return;
        }
        msg.setToUser(null);
        session.getAsyncRemote().sendText(JSONUtil.toJsonStr(msg, JSONConfig.create().setDateFormat("yyyy-MM-dd HH:mm:ss")));
    }

}
